﻿
function clearChildren(elem) {
    var eID = elem.attr('id');

    switch (eID) {
        case 'Region':
            clearChildren($("#District").val(""));
            break;
        case 'District':
            clearChildren($("#LagerLocality").val(""));
            break;
        case 'LagerLocality':
            clearChildren($("#SmallLocality").val(""));
            break;
        case 'SmallLocality':
            clearChildren($("#Street").val(""));
            break;       
        default:
    }
}


// получить ИД родителя для элемента elem
function getPGuid(elem) {
    var p = elem.attr("pguid");
    return p;
}

//получить ИД нас. пункта для поиска улиц
function getPGuidForStreet() {
    var sl = $("#SmallLocality");
    var ll = $("#LagerLocality");

    return sl.val() ? sl.attr('aoguid') :
        (ll.val() ? ll.attr('aoguid') : null);
}

function onSelect(elem, addrObj) {
    elem.attr("aoguid", addrObj.AoGuid);
    elem.attr("pGuid", addrObj.ParentGuid);
    elem.attr("regCode", addrObj.RegionCode);
    elem.attr("postCode", addrObj.PostalCode);

    if (addrObj.PostalCode)
        $("#PostalCode").val(addrObj.PostalCode);
    //clearChildren($("#Region"));
}

function findAndSet(elem, aoguid) {
    
    if()
    $.get('/Fias/GetAddrObj', { 'id': aoguid },
        function (data) {
            var obj = data;
            elem.val(obj.OffName + " " + obj.ShortName);
            onSelect(elem, obj);
            //elem.attr('aoguid', obj.AoGuid);
        }, 'json')
        .fail(function (a, b, c) {
            alert("error: " + a + ", " + b + ", " + c);
        });
}

function ajaxGetSource(action, term, count, response, pGuid, regCode) {
    var action = '/Fias/' + action;

    $.ajax({
        url: action,
        type: 'POST',
        dataType: 'json',
        data: { 'term': term, 'count': count, 'pGuid': pGuid, 'regCode': regCode },
        success: function (data) {
            response($.map(data, function (item) {

                return {
                    label: item.OffName + " " + item.ShortName + " (" + item.RegionCode + (item.ParentName ? ', ' + item.ParentName : '') + ")",
                    value: item.OffName + " " + item.ShortName,
                    'AoGuid': item.AoGuid,
                    'ParentGuid': item.ParentGuid,
                    'RegionCode': item.RegionCode,
                    'PostalCode': item.PostalCode
                };
            }));
        }
    });
}

